package com.leyou.privilege.interceptor;

import com.leyou.common.auth.entity.AppInfo;
import com.leyou.common.auth.entity.PayLoad;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.privilege.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by IntelliJ IDEA.
 *
 * @author: wangzibeng
 * Date: 2019/5/16 0016
 * Time: 16:46
 */

@Slf4j
public class PrivilegeHandlerInterceptor implements HandlerInterceptor {

    private JwtProperties prop;

    /**
     * 不能通过@Autowired
     */
    public PrivilegeHandlerInterceptor(JwtProperties prop) {
        this.prop = prop;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            // 获取请求头
            String token = request.getHeader(prop.getPrivilege().getHeaderName());
            // 校验
            PayLoad<AppInfo> payLoad = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), AppInfo.class);
            // TODO 获取token中的服务信息,做细粒度认证
            AppInfo userInfo = payLoad.getUserInfo();
            log.info("服务{}正在请求资源:{}", userInfo.getServiceName(), request.getRequestURI());
            return true;
        } catch (Exception e) {
            log.error("服务访问被拒绝,token认证失败!", e);
            return false;
        }
    }
}
